package com.jetinno.jetinnosystemclient;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by zhangyuncai on 2022/11/24.
 */
public class ClientProcessUtils {

    private static ClientProcessUtils _instance;

    public static ClientProcessUtils getInstance() {
        if (_instance == null) {
            synchronized (ClientProcessUtils.class) {
                if (_instance == null) {
                    _instance = new ClientProcessUtils();
                }
            }
        }
        return _instance;
    }

    private Process process;

    /**
     * 结束进程,执行操作调用即可
     */
    public void exitApp(String packageName) {
        initProcess();
        killProcess(packageName);
        close();
    }

    /**
     * 初始化进程
     */
    private void initProcess() {
        if (process == null) {
            try {
                process = Runtime.getRuntime().exec("su");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 结束进程
     */
    private void killProcess(String packageName) {
        if (process == null) {
            initProcess();
        }
        if (process != null) {
            OutputStream out = process.getOutputStream();
            String cmd = "am force-stop " + packageName + " \n";
            try {
                out.write(cmd.getBytes());
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     */
    private void close() {
        if (process != null)
            try {
                process.getOutputStream().close();
                process = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}
